package org.jeecg.modules.demo.socost.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.socost.entity.SoCost;
import org.jeecg.modules.demo.socost.service.ISoCostService;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: so_cost
 * @Author: jeecg-boot
 * @Date:   2021-12-08
 * @Version: V1.0
 */
@Api(tags="so_cost")
@RestController
@RequestMapping("/socost/soCost")
@Slf4j
public class SoCostController extends JeecgController<SoCost, ISoCostService> {
	@Autowired
	private ISoCostService soCostService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private IPuBuyOrderService puBuyOrderService;

	 private static final String TITLE = "单据审核";




	private String getMessage(String name,String date) {
		String str ="由【"+name+"】于【"+date+"】发起的采购费用单需要您的审核，请及时查看！";
		return str;
	}


	/**
	 * 分页列表查询
	 *
	 * @param soCost
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购费用单-分页列表查询")
	@ApiOperation(value="采购费用单-分页列表查询", notes="采购费用单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/socost/SoCostList")
	public Result<?> queryPageList(SoCost soCost,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<SoCost> queryWrapper = QueryGenerator.initQueryWrapper(soCost, req.getParameterMap());
			queryWrapper.eq("SHANCHU",0);
			Page<SoCost> page = new Page<SoCost>(pageNo, pageSize);
			IPage<SoCost> pageList = soCostService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	/**
	 *   添加
	 *
	 * @param soCost
	 * @return
	 */
	@AutoLog(value = "采购费用单-添加")
	@ApiOperation(value="采购费用单-添加", notes="采购费用单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SoCost soCost,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			String str = soCostService.getMaxCode();
			Map<String,String> map = new HashMap<>();
			if(str==null){
				map.put("maxCode",null);
			}else{
				map.put("maxCode",str);
			}
			String name = precode+"FY_";
			String resultCode = generateOddUtil.createCode(map,name);
			soCost.setSocCostNo(resultCode);
			soCost.setApportionstate(0);
			soCost.setShenhe(0);
			soCost.setShanchu(0);
			soCost.setCreateTime(new Date());
			soCost.setSyje(soCost.getPsAmount());

			LoginUser user = sysBaseAPI.getUserById(soCost.getSalesman());
			TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
			templateMessageDTO.setFromUser("管理员");
			templateMessageDTO.setToUser(soCost.getCheckmen()+",");
			templateMessageDTO.setTitle(TITLE);
			templateMessageDTO.setTemplateCode("order");
			Map<String, String> templateParam = new HashMap<>();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date= simpleDateFormat.format(new Date());
			templateParam.put("ts_date",date);
			templateParam.put("ts_content", getMessage(user!=null?user.getRealname():"业务员不存在！", date));
			templateParam.put("checkOrder",soCost.getSocCostNo());
			templateParam.put("cd_url","/socost/soCost/list");
			templateMessageDTO.setTemplateParam(templateParam);
			sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
			soCostService.save(soCost);
			return Result.OK("成功！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"系统错误！");
		}
	}

	 /**
	  *  审核
	  *
	  * @param soCost
	  * @return
	  */
	 @AutoLog(value = "采购费用单-审核")
	 @ApiOperation(value="采购费用单-审核", notes="采购费用单-审核")
	 @PostMapping(value = "/checkcost")
	 public Result<?> checkcost(@RequestBody SoCost soCost) {
	 	try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			if(!sysUser.getId().equals(soCost.getCheckmen())){
				return Result.error(500,"您不是当前单据的指定审核人！");
			}
			if(soCost.getShenhe()==1){
				return Result.error(300,"已审核，无需重复审核！");
			}

			soCost.setShenhe(1);
			soCost.setShTime(new Date());
			soCostService.updateById(soCost);
			return Result.OK("审核成功!");
		}catch (Exception e){
	 		e.printStackTrace();
	 		return Result.error(500,"系统错误！");
		}
	 }
	 /**
	  *  弃审
	  *
	  * @param soCost
	  * @return
	  */
	 @AutoLog(value = "采购费用单-弃审")
	 @ApiOperation(value="采购费用单-弃审", notes="采购费用单-弃审")
	 @PostMapping(value = "/waviecheckcost")
	 public Result<?> waviecheckcost(@RequestBody SoCost soCost) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(soCost.getCheckmen())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(soCost.getShenhe()==0){
				 return Result.error(300,"单据未审核，无法弃审");
			 }

			 if(soCost.getApportionstate()==1){
				 return Result.error(300,"单据已分摊，无法弃审");
			 }
			 soCost.setShenhe(0);
			 soCost.setShTime(null);
			 soCostService.updateById(soCost);
			 return Result.OK("弃审成功!");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }

	/**
	 *  编辑
	 *
	 * @param soCost
	 * @return
	 */
	@AutoLog(value = "采购费用单-编辑")
	@ApiOperation(value="采购费用单-编辑", notes="采购费用单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SoCost soCost) {
		try{
			soCostService.updateById(soCost);
			return Result.OK("编辑成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购费用单-通过id删除")
	@ApiOperation(value="采购费用单-通过id删除", notes="采购费用单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			SoCost soCost = soCostService.getById(id);
			if(soCost.getShenhe()==1){
				return Result.error(300,"单据已审核，无法删除!");
			}
			soCost.setShanchu(1);
			soCostService.removeById(soCost.getId());
			return Result.OK("删除成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购费用单-批量删除")
	@ApiOperation(value="采购费用单-批量删除", notes="采购费用单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.soCostService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购费用单-通过id查询")
	@ApiOperation(value="采购费用单-通过id查询", notes="采购费用单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SoCost soCost = soCostService.getById(id);
		if(soCost==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(soCost);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param soCost
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SoCost soCost) {
        return super.exportXls(request, soCost, SoCost.class, "so_cost");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SoCost.class);
    }

}
